package com.duplicall.yeb.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author yafengliang@yeah.net
 * @Description 验证码
 * @date 2021/5/19 14:16
 */
@RestController
@Slf4j
public class CaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @ApiOperation(value = "验证码")
    @GetMapping(value = "/captcha",produces = "image/jpeg")
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");
        //--------------------生成验证码Begin------------------------
        // 获取验证码文本内容
        String capText = defaultKaptcha.createText();
        log.info("capText:{}",capText);
        // 文本内容放进session
        request.getSession().setAttribute("captcha", capText);
        // 根据文本内容创建图文验证码
        BufferedImage bi = defaultKaptcha.createImage(capText);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            //输出图片
            ImageIO.write(bi, "jpg", out);
            out.flush();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //--------------------生成验证码end------------------------
    }

}
